<template>
  <div>
    <el-form style=" align-items: center; gap: 16px; margin-bottom: 20px;">
      <el-input v-model="filters.clientName" placeholder="客户姓名" class="filter-input" @input="handleFiltersChange" style="margin-left: 16px; width: 150px;"></el-input>
    </el-form>

    <!--  客户信息列表  -->
    <el-table :data="arr" stripe border :row-key="'clientId'" >
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="clientName" label="客户姓名"></el-table-column>
      <el-table-column prop="clientGender" label="性别"></el-table-column>
      <el-table-column prop="clientAge" label="年龄" ></el-table-column>
      <el-table-column prop="dateOfBirth" label="出生日期" width = "200"></el-table-column>
      <el-table-column prop="bloodType" label="血型" ></el-table-column>
      <el-table-column prop="familyMember" label="家属" ></el-table-column>
      <el-table-column prop="clientPhone" label="电话号码" width = "150"></el-table-column>
      <el-table-column prop="careLevelName" label="护理级别"></el-table-column>
      <el-table-column label="护理记录" width = "200">
        <template #default="{ row, rowIndex }">
          <el-button size="small" type="primary" @click="seeCareRecord(row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="日常护理" width = "200">
        <template #default="{ row, rowIndex }">
          <el-button size="small" type="success" @click="seeClientCareItem(row)">查看护理项目</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 客户列表分页 -->
    <div class="pagination-container" style="margin-top: 20px; display: flex; justify-content: left;">
      <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="clientPagination.total"
          v-model:current-page="clientPagination.current"
          v-model:page-size="clientPagination.size"
          :page-sizes="[1, 10, 20, 50]"
          @current-change="handleClientPageChange"
          @size-change="handleClientSizeChange"
      />
    </div>

    <!-- 查看客户护理项目对话框 -->
    <el-dialog title="客户护理项目" v-model="seeClientCareItemDialogVisible" width="50%">
      <el-table
          :data="clientCareItems"
          stripe border
          highlight-current-row
          style="align-items: center; gap: 16px; width: 100%; margin-bottom: 20px;"
          max-height="400px"
      >
<!--      <el-table :data="clientCareItems" highlight-current-row>-->
        <el-table-column type="index" label="序号" width="55" />
        <el-table-column prop="servicePurchaseDate" label="购买服务日期" width = "150"/>
        <el-table-column prop="serviceCount" label="护理数量" width = "90"/>
        <el-table-column prop="serviceEndDate" label="服务到期日期" width = "110"/>
        <el-table-column prop="careItemName" label="护理项目" width = "120"/>
        <el-table-column prop="careLevelName" label="护理级别" />
        <el-table-column prop="serviceStatus" label="服务项目状态" width = "110"/>
        <el-table-column label="操作" width = "100">
          <template #default="{ row, rowIndex }">
            <el-button size="small" type="primary" @click="addCareRecord(row)">进行护理</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 进行护理添加护理记录对话框 -->
    <el-dialog title="护理记录" v-model="addCareRecordDialogVisible" width="40%">
      <el-form :model="addCareRecordDialogData" label-width="120px">
        <el-form-item label="护理项目">
          <el-input v-model="addCareRecordDialogData.careItemName" disabled></el-input>
        </el-form-item>
        <el-form-item label="护理数量">
          <el-input v-model="addCareRecordDialogData.careCount"></el-input>
        </el-form-item>
        <el-form-item label="护理内容">
          <el-input v-model="addCareRecordDialogData.careContent"></el-input>
        </el-form-item>
<!--&lt;!&ndash;        显示护理人员默认为登录人员姓名&ndash;&gt;-->
<!--        <el-form-item label="护理人员ID">-->
<!--          <el-input v-model="addCareRecordDialogData.adId"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="客户">
          <el-input v-model="addCareRecordDialogData.clientName" disabled></el-input>
        </el-form-item>
        <el-form-item label="护理时间">
          <el-date-picker
              v-model="addCareRecordDialogData.careTime"
              type="datetime"
              placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addCareRecordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddCareRecord">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看客户护理记录对话框 -->
    <el-dialog title="客户护理记录" v-model="seeCareRecordDialogVisible">
      <el-table
          :data="clientCareRecords"
          stripe border
          highlight-current-row
          style="align-items: center; gap: 16px;  margin-bottom: 20px;"
          max-height="400px"
      >
<!--      <el-table :data="clientCareRecords" highlight-current-row>-->
        <el-table-column type="index" label="序号" width="60"/>
        <el-table-column prop="careItemName" label="护理项目" width="120"/>
        <el-table-column prop="careTime" label="护理时间" width="200"/>
        <el-table-column prop="careCount" label="护理数量" width="100"/>
        <el-table-column prop="careContent" label="护理内容" />
        <el-table-column prop="adName" label="护理人员" width="100"/>
        <el-table-column label="操作" width = "80">
          <template #default="{ row, rowIndex }">
            <el-button size="small" type="danger" @click="removeCareRecord(row,row.careRecordId)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, inject, reactive, onMounted, computed} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'



const filters = reactive({
  clientId: '', // 客户ID
  clientType: '', // 客户类型
  clientName: '', // 客户姓名
  clientAge: '', // 客户年龄
  dateOfBirth: '', // 出生日期
  clientGender: '', // 客户性别
  clientCardNumber: '', // 身份证号
  bloodType: '', // 血型
  familyMember: '', // 家属
  clientPhone: '', // 电话号码
  careLevelId: '', // 护理级别ID
  careAdminId: '', // 护理管理员ID
  bedId: '', // 床位ID
  // careLevelName: ''// 护理级别名称
});



// 移除客户护理记录
async function removeCareRecord(row,careRecordId) {
  try {
    // 确认是否移除
    await ElMessageBox.confirm('确认移除该客户护理记录？', '提示', { type: 'warning' });
    // 发送请求到后端
    const url = `CareRecordController/deleteCareRecord?careRecordId=${careRecordId}`;
    const responseData = await axios.post(url);
    // 检查返回的数据
    if (responseData) {
      // 移除成功
      ElMessage.success('移除成功');
      // 重新获取护理记录列表
      seeCareRecord(row);
    } else {
      // 移除失败
      ElMessage.error('移除失败：未返回有效数据');
    }
  } catch (error) {
    // 捕获错误
    console.error('移除护理记录时发生错误：', error);
    ElMessage.error('移除失败：' + (error.message || '未知错误'));
  }
  init();
}



// 添加客户护理记录
const addCareRecordDialogVisible = ref(false)
const addCareRecordDialogData = reactive({
  // careRecordId: 0, // 护理记录ID
  careItemName: "",
  careItemId: 1, // 护理项目ID
  careCount: 1, // 护理数量
  careRecordStatus: 1, // 状态（例如 1:显示, 0:隐藏）
  careContent: '', // 护理内容
  adId: localStorage.getItem("adminId"), // 护理人员ID
  clientId: 0, // 客户ID
  clientName: "",
  careTime: '' // 护理时间
});
const clientCareItemId = ref()
const preCount = ref()
const nowCount = ref()
const serviceEndDate = ref()
// 显示添加护理记录对话框
function addCareRecord(row) {
  addCareRecordDialogData.clientName = clientName
  addCareRecordDialogData.careItemName = row.careItemName
  addCareRecordDialogData.careItemId = row.careItemId
  addCareRecordDialogData.careCount = 1
  addCareRecordDialogData.adId = localStorage.getItem("adminId")
  addCareRecordDialogData.clientId = row.clientId
  addCareRecordDialogData.careTime = new Date().toISOString();
  addCareRecordDialogVisible.value = true
  clientCareItemId.value=row.clientCareItemId
  serviceEndDate.value=row.serviceEndDate
  preCount.value=row.serviceCount
  console.log(preCount.value)
}
// 提交添加护理记录请求
async function submitAddCareRecord() {
  try {
    console.log(addCareRecordDialogData)
    const response = await axios.post('CareRecordController/addCareRecord', addCareRecordDialogData);
    if (response) {
      ElMessage.success('护理记录添加成功')
      addCareRecordDialogVisible.value = false
      console.log(addCareRecordDialogData.careCount)
      nowCount.value=Number(preCount.value) - Number(addCareRecordDialogData.careCount);
      console.log(clientCareItemId.value,nowCount.value)
      const res = await axios.post('ClientCareItemController/updateClientCareItem', {
        clientCareItemId: clientCareItemId.value,
        serviceCount: nowCount.value,
        serviceEndDate: serviceEndDate.value
      })
      console.log(res)
      // 重新获取护理项目列表(客户护理项目列表显示更新（续费）后的客户护理项目)
      seeClientCareItem(clientCareItems.value.find(item => item.clientCareItemId === clientCareItemId.value));
    } else {
      ElMessage.error('添加护理记录失败：未返回有效数据')
    }
  } catch (error) {
    console.error('添加护理记录失败：', error)
    ElMessage.error('添加护理记录失败：' + (error.message || '未知错误'))
    console.log(res)
  }
  init();
}


const clientName = ref()
// 查看客护理项目
// 激活的护理项目列表
const clientCareItems = ref([]);
const seeClientCareItemDialogVisible = ref(false)
// 点击日常护理栏“查看护理项目”按钮所触发的事件
async function seeClientCareItem(row) {
  try {
    // 获取激活的护理项目列表
    clientName.value = row.clientName;
    const url = 'ClientCareItemController/getClientCareItemsByClientId';
    clientCareItems.value = await axios.get(url, {
      params: {
        clientId: row.clientId
      }
    });
    // 显示护理项目配置对话框
    seeClientCareItemDialogVisible.value = true;
  } catch (error) {
    console.error('获取客户护理项目失败：', error);
    ElMessage.error('获取客户护理项目失败：' + (error.message || '未知错误'));
    seeClientCareItemDialogVisible.value = true;
    clientCareItems.value=[];
  }
}


// 客户列表分页功能
const clientPagination = reactive({ current: 1, size: 10, total: 0 })
function handleClientPageChange(p) {
  clientPagination.current = p; init()
}
function handleClientSizeChange(s) {
  clientPagination.size = s; clientPagination.current = 1; init()
}


// 处理筛选信息，重新调用初始化客户信息列表
function handleFiltersChange() {
  init()
}


// 初始化显示类型为护理老人的客户信息
// 引入全局注入的 axios 对象
const axios = inject('axios')
let arr = ref([])
const init = async () => {
  let url = `client/searchByNameAndCareTypeAndAdId`;
  const params = {
    clientName: filters.clientName,
    page: clientPagination.current, // 添加分页参数 current
    size: clientPagination.size,
    adId: localStorage.getItem('adminId')// 添加健康管家参数
  };
  try {
    const data = await axios.get(url, { params });
    arr.value = data.records
    clientPagination.total = data.total
    console.log('chongg', arr.value) // 打印查看数据
  } catch (error) {
    console.log(error)
    ElMessage.error(error.message || '获取数据失败')
    arr.value = []; // 确保在获取数据失败时，arr 为空数组
  }
}
// 调用初始化函数，在页面载入前把数据从后台拉取到前端
onMounted(init)


// 查看客户护理记录
// 客户护理记录列表
const clientCareRecords = ref([]);
const seeCareRecordDialogVisible = ref(false)
// 点击护理记录栏“查看”按钮所触发的事件
async function seeCareRecord(row) {
  try {
    // 获取护理记录列表
    const url = 'CareRecordController/getCareRecordByClientId';
    clientCareRecords.value = await axios.get(url, {
      params: {
        clientId: row.clientId
      }
    });
    // 格式化护理时间
    const formattedRecords = clientCareRecords.value.map(record => {
      const date = new Date(record.careTime); // 假设护理时间字段名为 careTime
      const formattedDate = formatDate(date);
      return { ...record, careTime: formattedDate };
    });

    // 显示护理记录对话框
    clientCareRecords.value = formattedRecords;
    // 显示护理记录对话框
    seeCareRecordDialogVisible.value = true;
  } catch (error) {
    console.error('获取客户护理记录失败：', error);
    ElMessage.error('获取客户护理记录失败：' + (error.message || '未知错误'));
    seeCareRecordDialogVisible.value = true;
    clientCareRecords.value=[];
  }
}
// 数据库时间转换
function formatDate(date) {
  let year = date.getFullYear();
  let month = (date.getMonth() + 1).toString().padStart(2, '0');
  let day = date.getDate().toString().padStart(2, '0');
  let hours = date.getHours().toString().padStart(2, '0');
  let minutes = date.getMinutes().toString().padStart(2, '0');
  let seconds = date.getSeconds().toString().padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}


</script>

<style scoped>

</style>